package org.example.practice.about_properties;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 统一初始化properties文件-->根据yml中环境配置，更改properties配置
 * @Author: WangShengJie
 * @Date: 2025/4/18
 */
@Component
@Slf4j
public class WriteProperties {

    @Value("${parameters.properties.environment}")
    private String properties_environment;

    @PostConstruct  //初始化
    public void writeToProperties() {
        Properties properties = new Properties();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("src/main/resources/demo.properties");
            properties.setProperty("properties.environment", properties_environment);
            properties.store(out, "当前环境为：" + properties_environment);
            log.warn("初始化properties文件数据-->初始项：properties.environment=【{}】", properties_environment);
        } catch (FileNotFoundException e) {
            log.error("初始化properties文件数据-->失败", e);
        } catch (IOException ioException) {
            log.error("初始化properties文件数据-->失败", ioException);
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("初始化properties文件数据-->关闭数据源失败", e);
                }
            }
        }
    }
}
